package com.gofun.framework.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.gofun.framework.core.utils.BeanFactoryUtils;
import com.gofun.framework.core.utils.StringUtils;
import com.gofun.framework.web.property.PageProperties;

public class PageInterceptor implements HandlerInterceptor {
	
	final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		PageProperties properties = BeanFactoryUtils.getBean(PageProperties.class);
		Integer pageNum = getInteger(request.getParameter(properties.getCurrNumberName()));
		try {
			if(pageNum != null){
				Integer pageSize = getInteger(request.getParameter(properties.getPageSizeName()));
				PageHelper.startPage(pageNum, pageSize == null || pageSize < 1 ? properties.getPageSize() : pageSize, null);
			}
		} catch (Exception e) {
			
		}
		return true;
	}
	
	private Integer getInteger(String value){
		try {
			if(StringUtils.hasText(value))
				return Integer.parseInt(value);
		} catch (NumberFormatException e) {
			logger.error("parse page error :" + value);
		}
		return null;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView mav) throws Exception {
	}

}
